﻿using MQTTnet.Client;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MQTTnet.Client.Options;
using static AndroidX.ConstraintLayout.Core.State.State;

namespace HalkSee.Helper
{
    public class MqttHelper
    {
        private static MqttClient client;
        public static void Start(string host, int port, string clientid, string user, string pwd)
        {
            var factory = new MqttFactory();
            client = factory.CreateMqttClient() as MqttClient;

            var optionsBuilder = new MqttClientOptionsBuilder()
             .WithTcpServer(host, port)
             .WithClientId(clientid)
             .WithCleanSession(false)
             .WithKeepAlivePeriod(TimeSpan.FromSeconds(30));

            if (!string.IsNullOrEmpty(user))
                optionsBuilder = optionsBuilder.WithCredentials(user, pwd);

            var options = optionsBuilder.Build();

            int i = 1;
            client.UseConnectedHandler(async e =>
            {
                Console.WriteLine($"连接成功");
                statusChange?.Invoke(1);

                //监控器必须
                await client.SubscribeAsync($"/record/{InfoHelper.SN}/now"); //获取实时图片
                await client.SubscribeAsync($"/req/{InfoHelper.SN}/list"); //请求获取所有文件名
                await client.SubscribeAsync($"/req/{InfoHelper.SN}/file"); //请求获取一个文件
                //手机远程查看返回
                await client.SubscribeAsync($"/rsp/{InfoHelper.SN}/list"); //响应得到所有文件名
                await client.SubscribeAsync($"/rsp/{InfoHelper.SN}/file"); //响应得到一个文件
            })
            .UseDisconnectedHandler(e =>
            {
                Console.WriteLine($"连接断开{i++}");
                statusChange?.Invoke(-1);

                Task.Delay(5000).GetAwaiter().GetResult();
                Console.WriteLine($"开始连接");
                statusChange?.Invoke(0);
                client.ConnectAsync(options);
            })
            .UseApplicationMessageReceivedHandler(msg =>
            {
                Task.Run(() =>
                {
                    msgCallback?.Invoke(msg.ApplicationMessage.Topic, msg.ApplicationMessage.Payload);
                });
            });

            Console.WriteLine($"开始连接");
            statusChange?.Invoke(0);

            client.ConnectAsync(options);
        }

        public static async Task SubscribeAsync(string topic)
        {
            if (client != null && client.IsConnected)
                await client.SubscribeAsync(topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce);
        }

        public static async Task PublishAsync(string topic, byte[] data)
        {
            if (client != null && client.IsConnected)
                await client.PublishAsync(topic, data);
        }

        public static async Task DisconnectAsync()
        {
            if (client != null && client.IsConnected)
                await client.DisconnectAsync();
        }

        private static Action<int> statusChange { get; set; }
        public static void StatusChange(Action<int> callback)
        {
            statusChange = callback;
        }

        private static Action<string, byte[]> msgCallback { get; set; }
        public static void MsgCallback(Action<string, byte[]> callback)
        {
            msgCallback = callback;
        }
    }
}
